package com.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.portlet.PortletRequest;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.security.auth.PrincipalThreadLocal;

import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.comparator.PortletRenderWeightComparator;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;

/**
 * Servlet implementation class Download
 */
@WebServlet("/Download")
public class Download extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Download() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("inside download servlet..!!");
		//String queryString = request.getQueryString();
		//int k = queryString.indexOf("=");
		//long downloadId = Long.parseLong(queryString.substring(k+1));
		PrintWriter writer = response.getWriter();
		long docId = Long.parseLong(request.getParameter("docId"));
		long userId = Long.parseLong(request.getParameter("userId"));
		System.out.println("docId   "+docId);
		System.out.println("userId   "+userId);
		DLFileEntry dlFileEntry = null;
		//long userId = (java.lang.Long) request.getSession().getAttribute(WebKeys.USER_ID);
		/*ThemeDisplay td = (ThemeDisplay) req
				.getAttribute(WebKeys.THEME_DISPLAY);
		System.out.println("logged in user   "+td.getUserId());*/
		try
		{
			
			
			//User user = UserLocalServiceUtil.getUserpById(userId.longValue());
			dlFileEntry = DLFileEntryLocalServiceUtil.getDLFileEntry(docId);
			String mimeType = dlFileEntry.getMimeType();
			//PrincipalThreadLocal.setName(10903);  
			PrincipalThreadLocal.setName(userId);
			PermissionChecker permissionChecker = null;
			permissionChecker = PermissionCheckerFactoryUtil.create(UserLocalServiceUtil.getUser(dlFileEntry.getUserId()));
		
			PermissionThreadLocal.setPermissionChecker(permissionChecker);
			
			String fileName = dlFileEntry.getTitle();
			InputStream is = null;
			try
			{
				is = dlFileEntry.getContentStream();
				
			}
			catch(PortalException e)
			{
				if(e instanceof PrincipalException)
				{
					response.setContentType("text/html");
					writer.println("<h1>"+"HTTP Status 503 - Access Denied"+"</h1>");
					writer.close();
				}	
				e.printStackTrace();
			}
			catch(SystemException e)
			{
				e.printStackTrace();
			}
			response.setContentType(mimeType != null?mimeType:"application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=\""+fileName+"\"");
			ServletOutputStream os = response.getOutputStream();
			byte[] bufferData = new byte[1024];
			int read = 0;
			while((read=is.read(bufferData))!=-1)
			{
				os.write(bufferData,0 , read);
			}
			
			os.flush();
			os.close();
			is.close();
			System.out.println("download complete");
		}
		catch(Exception e)
		{
			System.out.println("resource does not exist");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.println("<h2>"+"file does not exist"+"</h2>");
		}
	}

	
}
